package com.example.userpage.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@Primary
@EnableJpaRepositories(
        basePackages = "com.example.userpage.repository", // 只扫描主库的Repository
        excludeFilters = @org.springframework.context.annotation.ComponentScan.Filter(
            type = org.springframework.context.annotation.FilterType.REGEX,
            pattern = "com\\.example\\.userpage\\.repository\\.votes\\..*"
        ),
        entityManagerFactoryRef = "messageEntityManagerFactory",
        transactionManagerRef = "messageTransactionManager"
)
public class MessageDataSourceConfig {

    @Primary
    @Bean(name = "messageDataSource")
    public DataSource messageDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/message?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai");
        dataSource.setUsername("root");
        dataSource.setPassword("//Sjj20051206");
        return dataSource;
    }

    @Primary
    @Bean(name = "messageEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean messageEntityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("messageDataSource") DataSource dataSource) {
        return builder
                .dataSource(dataSource)
                .packages("com.example.userpage.model")
                .persistenceUnit("message")
                .build();
    }

    @Primary
    @Bean(name = "messageTransactionManager")
    public PlatformTransactionManager messageTransactionManager(
            @Qualifier("messageEntityManagerFactory") LocalContainerEntityManagerFactoryBean messageEntityManagerFactory) {
        return new JpaTransactionManager(messageEntityManagerFactory.getObject());
    }
}